<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 头像显示 -->
      <img
        v-if="!avatar"
        class="avatar"
        src="../../assets/images/avatar.jpg"
        alt=""
      />
      <img v-else class="avatar" :src="avatar" alt="" />
      <!-- 两个按钮 -->
      <div class="btn-box">
        <input
          type="file"
          style="display: none"
          ref="fileRef"
          accept="image/*"
          @change="onFileChange"
        />
        <el-button type="primary" icon="el-icon-plus" @click="chooseImg"
          >选择图片</el-button
        >
        <el-button type="success" icon="el-icon-upload" :disabled="avatar === ''" @click="uploadFn">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
import { updateAvatarAPI } from '@/api'
export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    // 选择图片
    chooseImg () {
      this.$refs.fileRef.click()
    },
    // 图片已经选好后
    onFileChange (e) {
      // console.log(e.target.files)
      const files = e.target.files
      if (files.length === 0) {
        // 选择文件窗口打开后没有选择文件就点击确定了
      } else {
        const maxSize = 3670016
        if (files[0].size >= maxSize) {
          this.$message.warning('所选图片不能大于3.5M！请重新选择！')
          return false
        } else {
        // 选择了文件(默认只能选一个)
          // console.log(files[0])
          // 解决方案1：文件转链接
          // this.avatar = URL.createObjectURL(files[0])
          /*  console.log(this.avatar) */
          // 解决方案2：转成 base64 字符串
          const fr = new FileReader()
          fr.readAsDataURL(files[0]) // 传入文件对象开始读
          fr.onload = (e) => {
          // onload 等待把文件读成base64字符串后会再触发
          // e.target.result的值就是读完的结果
            this.avatar = e.target.result
          }
        }
      }
    },
    // 上传头像
    async uploadFn () {
      const { data: res } = await updateAvatarAPI(this.avatar)
      // console.log(res)
      if (res.code === 0) {
        this.$message.success(res.message)
        this.$store.dispatch('getUserInfoActions')
      } else {
        this.$message.error(res.message)
      }
    }
  }
}
</script>

<style scoped lang="less">
.avatar {
  width: 350px;
  height: 350px;
}
.btn-box {
  margin-top: 20px;
}
</style>
